from flask import Flask, Response, render_template, request, jsonify
import cv2
import threading
import time
from vehicle import VehicleController

app = Flask(__name__)
cap = cv2.VideoCapture(0)  # 使用第一个USB摄像头
controller = VehicleController()

# 全局变量
latest_frame = None
frame_lock = threading.Lock()

def capture_frames():
    global latest_frame
    while True:
        ret, frame = cap.read()
        if ret:
            _, buffer = cv2.imencode('.jpg', frame, 
                [int(cv2.IMWRITE_JPEG_QUALITY), 70])
            with frame_lock:
                latest_frame = buffer.tobytes()
        time.sleep(0.03)  # 约30FPS

@app.route('/')
def index():
    return render_template('index.html')

def generate():
    last_update = 0
    while True:
        with frame_lock:
            if latest_frame and time.time() - last_update > 0.033:
                yield (
                    b"--frame\r\n"
                    b"Content-Type: image/jpeg\r\n\r\n" 
                    + latest_frame + b"\r\n"
                )
                last_update = time.time()
        time.sleep(0.01)

@app.route('/video_feed')
def video_feed():
    return Response(
        generate(),
        mimetype='multipart/x-mixed-replace; boundary=frame'
    )

@app.route('/control', methods=['POST'])
def control():
    data = request.get_json()
    command = data.get('command', '')

    if command == 'forward':
        controller.forward()
    elif command == 'backward':
        controller.backward()
    elif command == 'stop':
        controller.stop()
    elif command == 'spin_left':
        controller.spin_left()
    elif command == 'spin_right':
        controller.spin_right()
    else:
        return jsonify({'status': 'error', 'message': 'Invalid command'}), 400

    return jsonify({'status': 'success', 'command': command})


if __name__ == '__main__':
    # 启动摄像头采集线程
    threading.Thread(target=capture_frames, daemon=True).start()
    app.run(host='0.0.0.0', port=8080, threaded=True)